<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>录制直播视频并下载</title>
	</head>
	<body>
		<h3>由于资源有限，此处的直播改由视频代替，主要是因为直播不需要video控件Controls，且没有绝对的路径指向可以直接下载，因此需要通过画布绘制的方式将其记录并生成媒体文件下载。</h3>
		<div class="video-area">
			<video width="400" height="300" src="bigocean.mp4" autoplay="autoplay" controls="controls" id="video"></video>
			<canvas id="canvas" width="400" height="300"></canvas>
			<button type="button" id="startRecording">开始录制</button>
			<button type="button" id="endRecording">结束录制</button>
		</div>
		<script src="whammy.js" type="text/javascript" charset="utf-8"></script>
		<script type="text/javascript">
			var video = new Whammy.Video(25); // 25表示帧率 25fps/1s
			var srcvideo = document.getElementById('video');
			var startBtn = document.getElementById('startRecording');
			var stopBtn = document.getElementById('endRecording');
			var requestId; // 定时器id
			startBtn.onclick = function startRecording() {
				console.log('开始录制');
				var canvas = document.getElementById('canvas');
				var context = canvas.getContext('2d');
				context.drawImage(srcvideo, 0, 0, canvas.width, canvas.height);
				video.add(context);
				requestId = setTimeout(function(){
					startRecording(srcvideo);
				}, 100);
			} 
			stopBtn.onclick = function() {
				console.log('结束录制')
				clearTimeout(requestId);
				finalizeVideo();
			}
			function finalizeVideo(){
			    video.compile(false, function(output){
				  var url = webkitURL.createObjectURL(output);
				  console.log("url:"+url);
				  blobDownloadVideo(url);
			  });
			}
			function blobDownloadVideo(url) {
			  const link = document.createElement('a');
			  link.style.display = 'none';
			  link.href = url;
			  link.download = 'video.mp4';
			  document.body.appendChild(link);
			  link.click();
			  link.remove();
			}
		</script>
	</body>
</html>
